package cn.sykj.car.shiro;

import cn.sykj.car.entity.Roles;
import cn.sykj.car.entity.Users;
import cn.sykj.car.jwt.JWTToken;
import cn.sykj.car.jwt.JWTUtil;
import cn.sykj.car.service.IOperationService;
import cn.sykj.car.service.IRolesService;
import cn.sykj.car.service.IUsersService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class MyRealm extends AuthorizingRealm {
    private static final Logger logger = LoggerFactory.getLogger(MyRealm.class);

    @Resource
    private IUsersService usersService;
    @Resource
    private IRolesService rolesService;
    @Resource
    private IOperationService operationService;

    /**
     *
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username = principals.toString();
        Users user = usersService.getUserByName(username);
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        List<Roles> rolesList = rolesService.getRolesByUser(user.getId());
        List<Integer> roleIds = new ArrayList<>();
        for (Roles roles : rolesList) {
            roleIds.add(roles.getId());
            simpleAuthorizationInfo.addRole(roles.getRoleName());
        }
        List<String> permissions = operationService.getPermissionCodesByRoles(roleIds);
        log.info("权限验证========================》"+ JSON.toJSONString(permissions));
//        if(permissions.size()==0){
//            throw new CommonException(StatusCode.UN_AUTHORIZED.getCode(),StatusCode.UN_AUTHORIZED.getMsg());
//        }
        simpleAuthorizationInfo.addStringPermissions(permissions);
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
        String token = (String) auth.getCredentials();
        // 解密获得username，用于和数据库进行对比
        String username = JWTUtil.getUsername(token);
        if (username == null) {
            throw new UnknownAccountException("token错误");
        }

        Users users = usersService.getUserByName(username);
        if (users == null) {
            throw new UnknownAccountException("用户不存在");
        }

        if (!JWTUtil.verify(token, username, users.getPasswd())) {
            throw new UnknownAccountException("用户名或密码错误");
        }

        return new SimpleAuthenticationInfo(username, token, "token_realm");
    }
}
